// 树结构转换功能实现

/**
 * 将树形结构转换为扁平数组
 * @param {Object} tree - 树形结构对象
 * @returns {Array} 转换后的扁平数组
 */
function treeToArray(tree) {
  let result = [];
  let queue = [];
  result.push({ id: tree.id, name: tree.name, parentId: 0 });
  queue.unshift({ id: tree.id, name: tree.name, children: tree.children });
  while (queue.length > 0) {
    const currentNode = queue.shift();
    if (currentNode.children && currentNode.children.length > 0) {
      for (let i = 0; i < currentNode.children.length; i++) {
        const childNode = currentNode.children[i];
        const { id, name } = childNode;
        queue.unshift(childNode);
        result.push({
          id,
          name,
          parentId: currentNode.id
        });
      }
    }
  }
  return result;
}

/**
 * 将扁平数组转换为树形结构
 * @param {Array} arr - 扁平数组
 * @returns {Object} 转换后的树形结构
 */
function arrayToTree(arr) {
  let map = new Map();
  let result = null;
  for (let i = 0; i < arr.length; i++) {
    const { id, name } = arr[i];
    const children = [];
    map.set(id, { id, name, children });
  }

  for (let i = 0; i < arr.length; i++) {
    const { parentId, id } = arr[i];
    if (parentId !== 0) {
      const parentNode = map.get(parentId);
      parentNode.children.push(map.get(id));
    } else {
      result = map.get(id);
    }
  }
  return result;
}

/**
 * 测试树结构转换功能
 */
function testTreeConversion() {
  // 测试数据
  const testTree = {
    id: 1,
    name: "部门A",
    children: [
      {
        id: 2,
        name: "部门B",
        children: [
          {
            id: 4,
            name: "部门D",
            children: [
              {
                id: 7,
                name: "部门G",
                children: [],
              },
              {
                id: 8,
                name: "部门H",
                children: [],
              },
            ],
          },
          {
            id: 5,
            name: "部门E",
            children: [],
          },
        ],
      },
      {
        id: 3,
        name: "部门C",
        children: [
          {
            id: 6,
            name: "部门F",
            children: [],
          },
        ],
      },
    ],
  };

  const testArray = [
    { id: 1, name: '部门A', parentId: 0 },
    { id: 2, name: '部门B', parentId: 1 },
    { id: 3, name: '部门C', parentId: 1 },
    { id: 4, name: '部门D', parentId: 2 },
    { id: 5, name: '部门E', parentId: 2 },
    { id: 6, name: '部门F', parentId: 3 },
    { id: 7, name: '部门G', parentId: 4 },
    { id: 8, name: '部门H', parentId: 4 }
  ];

  console.log('树转数组结果:');
  console.log(treeToArray(testTree));
  
  console.log('\n数组转树结果:');
  console.log(arrayToTree(testArray));
}

// 导出函数
module.exports = {
  treeToArray,
  arrayToTree,
  testTreeConversion
};